﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWebPagesStarterKit;
using System.Web.Security;
using MyWebPagesStarterKit.Controls;
using System.IO;
using System.Net.Mail;
using System.Net;

public partial class SectionControls_LoginForm : SectionControlBaseClass
{
    private string _returnURL = string.Empty;
    private LoginForm _section;

    protected void Page_Init(object sender, EventArgs e)
    {
        createUserWizard.CreatedUser += new EventHandler(createUserWizard_CreatedUser);

        if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["activate"]))
        {
            Guid userId = new Guid(Request.QueryString["activate"]);
            MembershipUser user = Membership.GetUser(userId);
            user.IsApproved = true;
            Membership.UpdateUser(user);

            Login1.UserName = user.UserName;

            Login1.FindControl("trActivationSuccess").Visible = true;
        }

        Login1.FindControl("trCreateUser").Visible = WebSite.GetInstance().AllowUserSelfRegistration;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      

        if (!IsPostBack)
        {
            Control ctl = Login1.FindControl("UserName");
            if (ctl != null)
            {
                (ctl).Focus();
            }

            //hack for maintaining the virtual url
            if (Session["OriginalURL"] != null)
                ViewState["ReturnURL"] = Session["OriginalURL"].ToString();
        }
        else
        {
            //hack for maintaining the virtual url
            if (ViewState["ReturnURL"] != null)
                _returnURL = ViewState["ReturnURL"].ToString();
        }
    }

    protected void OnLoggingIn(object sender, EventArgs e)
    {
        //hack for upper and lower case: the asp login control is case sensitive: Admin <> admin
        //in order to make it not case sensitive, we rewrite the UserName (as it should be) to the login control
        TextBox txtUserName = (TextBox)Login1.FindControl("UserName");
        foreach (MembershipUser user in Membership.GetAllUsers())
        {
            if (string.Compare(user.UserName, txtUserName.Text, true) == 0)
            {
                Login1.UserName = user.UserName;
                return;
            }
        }
    }

    /// <summary>
    /// hack for maintaining the virtual url
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void OnLoggedIn(object sender, EventArgs e)
    {
        if (_returnURL != string.Empty)
            Response.Redirect(_returnURL);
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        updateViews();
    }

    private void updateViews()
    {
        /// uploaded images get the placeholder {0} for the pageID. With the pageID the user access to the image can be evaluated.
        string pageId = Request.QueryString["pg"];

        if (Page.User.Identity.IsAuthenticated)
        {
            multiview.SetActiveView(editView);
        }
        else
        {
            if (ViewState["view"] != null)
            {
                switch (Convert.ToString(ViewState["view"]))
                {
                    case "ChangePassword":
                        multiview.SetActiveView(view2);
                        break;
                    case "CreateUser":
                        multiview.SetActiveView(view3);
                        break;
                }
            }
            else
            {
                multiview.SetActiveView(readonlyView);
            }
        }
    }

    protected void LogOut(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Response.Redirect("/");
    }

    protected void Action(object sender, CommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "ChangePassword":
                ViewState["view"] = "ChangePassword";
                break;
            case "CreateUser":
                ViewState["view"] = "CreateUser";
                break;
            case "Abandon":
                ViewState["view"] = null;
                break;
        }
    }

    void createUserWizard_CreatedUser(object sender, EventArgs e)
    {
        WebSite _website = WebSite.GetInstance();
        //Send email to user for verifying account
        MembershipUser user = Membership.GetUser(createUserWizard.UserName);
        string url = string.Concat("http://", Request.Url.Authority, Response.ApplyAppPathModifier("~/Login.aspx?activate="));

        MailMessage mail = new MailMessage(_website.MailSenderAddress, user.Email);
        mail.SubjectEncoding = System.Text.Encoding.UTF8;
        mail.Subject = string.Format(Resources.StringsRes.pge_UserRegistration_ActivationEmailSubject, _website.WebSiteTitle);
        mail.BodyEncoding = System.Text.Encoding.UTF8;
        mail.IsBodyHtml = false;
        mail.Body = string.Format(Resources.StringsRes.pge_UserRegistration_ActivationEmailBody, _website.WebSiteTitle, url, user.ProviderUserKey.ToString());

        SmtpClient client = new SmtpClient(_website.SmtpServer);

        //when Smtp user/password/domain is given, SMTP-Authentication has to be used
        if (_website.SmtpUser != "" && _website.SmtpPassword != "" && _website.SmtpDomain != "")
        {
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(_website.SmtpUser, _website.SmtpPassword, _website.SmtpDomain);
        }

        client.Send(mail);
    }


    public override ISection Section
    {
        set
        {
            if (value is LoginForm)
                _section = (LoginForm)value;
            else
                throw new ArgumentException("Section must be of type LoginForm");
        }
        get { return _section; }
    }

    public override bool HasAdminView
    {
        get { return false; }
    }

    public override string InfoUrl
    {
        get
        {
            string lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            if (File.Exists(HttpContext.Current.Server.MapPath(string.Format("Documentation/" + lang + "/quick_guide.html"))))
            {
                return "Documentation/" + lang + "/quick_guide.html#html-content";
            }
            else
            { return "Documentation/en/quick_guide.html#html-content"; }
        }
    }
}
